package com.easpeed.elevator.ui;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.util.Log;
import com.bigyu.utils.Logger;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.easpeed.elevator.bean.RouteBean;
import com.easpeed.elevator.utils.ChartUtil;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

public class WaterfallView extends View {

    private LinkedList<int[]> dvsList; // 使用 LinkedList 存储 dvs 数组
    private LinkedList<Long> timeList; // 使用 LinkedList 存储 time 数组
    private int selectedDvsIndex = -1; // 当前选中的 dvs 数组索引
    private int selectedX = -1; // 点击的 x 坐标
    private int selectedY = -1; // 点击的 y 坐标
    private boolean isClickable = false; // 开关变量
    private static final int MAX_DVS_COUNT = ChartUtil.fixedHeight; // 最大的 dvs 数组数量

    private Paint paint;
    Paint textPaint = new Paint();

    public WaterfallView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init() {
        dvsList = new LinkedList<>(); // 初始化 LinkedList
        timeList = new LinkedList<>(); // 初始化 LinkedList
        paint = new Paint();
        paint.setStyle(Paint.Style.STROKE);
        paint.setColor(Color.RED);
        paint.setPathEffect(new DashPathEffect(new float[]{10, 10}, 0));

        textPaint.setColor(Color.BLACK); // 文本颜色
        textPaint.setTextSize(18); // 字体大小
        textPaint.setAntiAlias(true); // 抗锯齿
        textPaint.setStyle(Paint.Style.FILL); // 填充样式
    }

    public void setBitmap(Bitmap bitmap) {
        bitmaps = new Bitmap[2];
        bitmaps[0] = bitmap;
        bitmaps[1] = Bitmap.createBitmap(ChartUtil.fixedWidth, ChartUtil.fixedHeight, Bitmap.Config.ARGB_8888);
        ;
        invalidate(); // 触发重绘
    }

    // 将新的 dvs 数组添加到 dvsList 中
    public void addDvs(int[] newDvs) {
        if (dvsList.size() >= MAX_DVS_COUNT) {
            dvsList.removeFirst(); // 移除最旧的 dvs 数组
            timeList.removeFirst();
        }
        dvsList.addLast(newDvs); // 添加新的 dvs 数组
        timeList.addLast(System.currentTimeMillis());
        dvsChange = true;

        updateWaterfallBitmap(getLatestDvs());
        invalidate(); // 触发重绘
    }

    public void setClickable(boolean clickable) {
        this.isClickable = clickable;
        if (!clickable) {
            selectedDvsIndex = -1; // 清除选中状态
            selectedX = -1;
            selectedY = -1;
            invalidate(); // 触发重绘以移除虚线
        }
        invalidate(); // 触发重绘
    }

    public void setExpand(int x1, int x2) {
        this.x1 = ChartUtil.dvsXToIndex(x1);
        this.x2 = ChartUtil.dvsXToIndex(x2);
        if (this.x2 > ChartUtil.fixedWidth) {
            this.x2 = ChartUtil.fixedWidth;
        }
    }

    int x1 = 0;
    int x2 = ChartUtil.fixedWidth;
    /**
     * 安全裁剪 Bitmap，防止越界
     *
     * @param bitmap 原始 Bitmap
     * @param x1     起始 x 坐标
     * @param x2     结束 x 坐标
     * @return 裁剪后的 Bitmap（宽度最小为 1）
     */
    public static Bitmap safeCropBitmap(Bitmap bitmap, int x1, int x2) {
        if (bitmap == null) return null;

        int width = bitmap.getWidth();
        int height = bitmap.getHeight();

        // 限制 x1 和 x2 在合法范围内
        int safeX1 = Math.max(0, Math.min(x1, width));
        int safeX2 = Math.max(0, Math.min(x2, width));

        int cropWidth = Math.max(1, safeX2 - safeX1);

        try {
            return Bitmap.createBitmap(bitmap, safeX1, 0, cropWidth, height);
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
            return null;
        }
    }
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        Bitmap originalBitmap = getOriginalBitmap();
        // 绘制原始位图

//        if (originalBitmap != null) {
//            if (x2 == ChartUtil.fixedWidth && x1 == 0) {
//                drawScaledBitmap(canvas, originalBitmap);
//            } else {
//                Bitmap croppedBitmap = Bitmap.createBitmap(originalBitmap, x1, 0, Math.max(x2 - x1, 1), originalBitmap.getHeight());
//                drawScaledBitmap(canvas, croppedBitmap);
//            }
//        }
        if (originalBitmap != null) {
            if (x2 == ChartUtil.fixedWidth && x1 == 0) {
                drawScaledBitmap(canvas, originalBitmap);
            } else {
                Bitmap croppedBitmap = safeCropBitmap(originalBitmap, x1, x2);
                if (croppedBitmap != null) {
                    drawScaledBitmap(canvas, croppedBitmap);
                }
            }
        }

        // 根据开关状态绘制虚线
        if (isClickable && selectedDvsIndex >= 0 && selectedX >= 0 && selectedY >= 0) {
            // 横线
            canvas.drawLine(0, selectedY, getWidth(), selectedY, paint);
            // 纵线
            canvas.drawLine(selectedX, 0, selectedX, getHeight(), paint);

            float x = 10; // 距离左边的边距
            float y = getHeight() - 10; // 距离底部的边距，避免文本被遮挡
            if (selectedDvsIndex < 0 || selectedDvsIndex >= dvsList.size() || dvsList.isEmpty()) {
                canvas.drawText("未选择有效点", x, y, textPaint);
                return;
            }
            // 计算实际的 x 坐标在原始数据中的位置
            int distanceX = (int) ChartUtil.dvsIndexToDistance(getSelectedDVSIndex());

            long timestamp = timeList.get(selectedDvsIndex);
            SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
            String timeFormatted = sdf.format(new Date(timestamp));
            String text = "选中距离: " + distanceX + "米" + ",所在时间：" + timeFormatted;
            // 计算文本在左下角的位置

            // 绘制文本
            canvas.drawText(text, x, y, textPaint);
//
//            // 计算虚线方框的坐标
//            int top = Math.max(0, selectedY - 20); // 上边界
//            int bottom = Math.min(getHeight(), selectedY + 20); // 下边界
//
//            // 前后 20 * 3 / λ 的宽度
//            float lambda = ChartUtil.lambd; // 假设 λ 的值
//            int left = Math.max(0, selectedX - (int)(20 * 3 / lambda)); // 左边界
//            int right = Math.min(getWidth(), selectedX + (int)(20 * 3 / lambda)); // 右边界
//
//            // 设置虚线画笔
//            paint.setStyle(Paint.Style.STROKE);
//            paint.setPathEffect(new DashPathEffect(new float[]{10, 10}, 0)); // 虚线效果
//
//            // 绘制虚线方框
//            canvas.drawLine(left, top, right, top, paint); // 上边
//            canvas.drawLine(left, bottom, right, bottom, paint); // 下边
//            canvas.drawLine(left, top, left, bottom, paint); // 左边
//            canvas.drawLine(right, top, right, bottom, paint); // 右边
//
//            // 重置画笔效果
//            paint.setPathEffect(null);
        }
    }

    public static void drawScaledBitmap(Canvas canvas, Bitmap croppedBitmap) {
        // 获取画布的宽度和高度
        int canvasWidth = canvas.getWidth();
        int canvasHeight = canvas.getHeight();

        // 直接绘制缩放后的位图
        canvas.drawBitmap(croppedBitmap, null, new Rect(0, 0, canvasWidth, canvasHeight), null);
    }


    private LinkedList<int[]> getLatestDvs() {
        return dvsList; // 获取最新的 dvs 数组
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (!isClickable) return false; // 如果不可点击，则直接返回

        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
            case MotionEvent.ACTION_MOVE:
                selectedX = (int) event.getX();
                selectedY = (int) event.getY();
                Logger.d("sheng", "selectX:" + selectedX + ",selectY:" + selectedY + ",x1:" + x1 + "，x2：" + x2);
                // 计算选中的 dvs 数组索引
                int height = getHeight();
                int listSize = dvsList.size();

                int yindex = selectedY * ChartUtil.fixedHeight / (height);
                if (yindex <= listSize) {
                    selectedDvsIndex = listSize - yindex;
                }

                invalidate(); // 触发重绘
                return true;
            case MotionEvent.ACTION_UP:
                break;
        }
        return super.onTouchEvent(event);
    }

    public boolean dvsChange = false;
    public Bitmap[] bitmaps;
    private int currentIndex = 0;

    public Bitmap getOriginalBitmap() {
        return bitmaps[currentIndex];
    }

    public Bitmap getNextBitmap() {
        return bitmaps[(currentIndex + 1) % 2];
    }

    public void addCurrentIndex() {
        currentIndex = (currentIndex + 1) % 2;
    }

//    public void updateWaterfallBitmap(LinkedList<int[]> dvsList) {
//        // 检查 dvsList 是否为空
//        if (!dvsChange) {
//            return ;
//        }
//
//        int height = ChartUtil.fixedHeight;  // 固定行数
//        int width = ChartUtil.fixedWidth;
//
//        Canvas canvas = new Canvas(getNextBitmap());
//        Paint paint = new Paint();
//
//        // 将 originalBitmap 的内容绘制到新位图中，删除最后一行
//        Rect srcRect = new Rect(0, 0, width, height - 1); // 从第一行开始
//        Rect destRect = new Rect(0, 1, width, height); // 向下移动一行
//        canvas.drawBitmap(getOriginalBitmap(), srcRect, destRect, null);
//
//        if (!dvsList.isEmpty()) {
//            dvsChange = false;
//            // 获取最新的 DVS 数据
//            int[] latestDvs = dvsList.getLast();
//            for (int rolX = 0; rolX < width; rolX++) {
////                int data = 0;
////                int dvsIndex = ChartUtil.dvsXToIndex(rolX);
////                if (dvsIndex < 0 || dvsIndex >= latestDvs.length) {
////                    continue; // 确保索引有效
////                }
//                int data = latestDvs[rolX];
//
//                // 获取颜色并绘制
//                int color = ChartUtil.ColorRules(data);
//                paint.setColor(color);
//                canvas.drawPoint(rolX, 0, paint); // 绘制到第一行
//            }
//        }
//
//        addCurrentIndex();
//    }

    private static final int DRAW_HEIGHT = 1; // 只保留最近的几个值
    private static final int HISTORY_SIZE = 3; // 只保留最近的几个值
    private LinkedList<int[]> historyDvsList = new LinkedList<>();

    public void updateWaterfallBitmap(LinkedList<int[]> dvsList) {
        // 检查 dvsList 是否为空
        if (!dvsChange) {
            return;
        }

        int height = ChartUtil.fixedHeight;  // 固定行数
        int width = ChartUtil.fixedWidth;

        Canvas canvas = new Canvas(getNextBitmap());
        Paint paint = new Paint();

        // 将 originalBitmap 的内容绘制到新位图中，删除最后几行
        Rect srcRect = new Rect(0, 0, width, height - DRAW_HEIGHT); // 从第一行开始
        Rect destRect = new Rect(0, DRAW_HEIGHT, width, height); // 向下移动 DRAW_HEIGHT 行
        canvas.drawBitmap(getOriginalBitmap(), srcRect, destRect, null);

        if (!dvsList.isEmpty()) {
            dvsChange = false;
            // 获取最新的 DVS 数据
            int[] latestDvs = dvsList.getLast();

            // 保存历史数据
            if (historyDvsList.size() >= HISTORY_SIZE) {
                historyDvsList.removeFirst(); // 保持固定数量的历史记录
            }
            historyDvsList.add(latestDvs.clone()); // 深拷贝以避免修改

            // 使用临时数组来存储颜色值
            int[] colors = new int[width];

            // 获取颜色并填充到临时数组
            for (int rolX = 0; rolX < width; rolX++) {
                colors[rolX] = ChartUtil.getColorFromValue(latestDvs[rolX]);
            }

            // 平滑插值
            for (int rolX = 0; rolX < width; rolX++) {
                int avgValue = latestDvs[rolX]; // 默认使用最新值

                // 计算最近几个历史值的简单平均
                for (int h = 0; h < HISTORY_SIZE && h < historyDvsList.size(); h++) {
                    avgValue += historyDvsList.get(historyDvsList.size() - 1 - h)[rolX];
                }
                avgValue /= (HISTORY_SIZE + 1); // 加上最新值的数量

                // 获取颜色
                int color = ChartUtil.getColorFromValue(avgValue);
                paint.setColor(color);

                // 绘制
                for (int h = 0; h < DRAW_HEIGHT; h++) {
                    canvas.drawPoint(rolX, h, paint);
                }
            }
        }

        addCurrentIndex();
    }


    // 查找最大值的方法
    // 查找最大值的方法
    public int[] findMaxDvsValue() {
        int max = Integer.MIN_VALUE;
        int maxIndex = -1;
        int width = 20; // 查找范围

        // 确保当前选中的 DVS 数组索引有效
        if (selectedDvsIndex < 0 || selectedDvsIndex >= dvsList.size() || dvsList.isEmpty()) {
            return new int[]{max, maxIndex}; // 返回初始值
        }

        int scaledX = getSelectedDVSIndex();
        Logger.d("sheng", "x:" + selectedX + ", scaledX:" + scaledX + ", selectedDVs:" + selectedDvsIndex + ", lens:" + dvsList.size());

        // 遍历左右各 20 个点及前后 20 个 dvs 数组
        for (int i = Math.max(0, selectedDvsIndex - width); i <= Math.min(dvsList.size() - 1, selectedDvsIndex + width); i++) {
            int[] currentDvs = dvsList.get(i);
            int xindex = scaledX;

            if (currentDvs.length < xindex) {
                continue;
            }
            Logger.d("sheng", "currentDvs:" + currentDvs.length + ", len:" + currentDvs.toString());

            // 确保在有效的范围内
            for (int j = Math.max(0, xindex - width); j <= Math.min(currentDvs.length - 1, xindex + width); j++) {
                // 查找最大值
                if (currentDvs[j] > max) {
                    max = currentDvs[j];
                    maxIndex = j; // 更新最大值所在的 DVS 的索引
                }
            }
        }
        return new int[]{max, (int) (ChartUtil.dvsIndexToDistance(maxIndex))}; // 返回最大值和索引
    }


    public List<RouteBean> getRouteBeanList() {

        List<RouteBean> routeBeanList = new LinkedList<>();
        int max = Integer.MIN_VALUE;
        int width = 20; // 查找范围

        // 确保当前选中的 DVS 数组索引有效
        if (selectedDvsIndex < 0 || selectedDvsIndex >= dvsList.size() || dvsList.isEmpty()) {
            return routeBeanList; // 返回初始值
        }

        int scaledX = getSelectedDVSIndex();
        Logger.d("sheng", "x:" + selectedX + ", scaledX:" + scaledX + ", selectedDVs:" + selectedDvsIndex + ", lens:" + dvsList.size());

        // 遍历左右各 20 个点及前后 20 个 dvs 数组
        for (int i = Math.max(0, selectedDvsIndex - width); i <= Math.min(dvsList.size() - 1, selectedDvsIndex + width); i++) {
            int[] currentDvs = dvsList.get(i);
            if (currentDvs == null) {
                continue;
            }
            int xindex = scaledX;

            if (currentDvs.length < xindex) {
                continue;
            }

            // 确保在有效的范围内
            for (int j = Math.max(0, xindex - width); j <= Math.min(currentDvs.length - 1, xindex + width); j++) {
                // 查找最大值
                if (currentDvs[j] > max) {
                    max = currentDvs[j];
                    //找到更大的数据，需要清除之前较小数据集合
                    routeBeanList.clear();
                }
                if (currentDvs[j] == max) {
                    float distance =  (ChartUtil.dvsIndexToDistance(j)) / 1000;
                    routeBeanList.add(new RouteBean("" + max, "" + distance));
                }
            }
        }
        return routeBeanList;
    }


    public int getSelectedDVSIndex() {
        return x1 + (x2 - x1) * selectedX / getWidth();
    }
}
